let categoryId = getQueryString("categoryId");

$(function () {
	vm.categoryId = categoryId;
    $("#jqGrid").Grid({
        url: '../goods/listc/' + vm.categoryId,
        colModel: [
            {label: 'id', name: 'id', index: 'id', key: true},
            {label: '类型', name: 'typeName', index: 'goods_type', width: 50},
	        {label: '书名', name: 'categoryName', index: 'category_id', width: 80},
            {label: '章节名称', name: 'name', index: 'name', width: 160},
            {label: '作者', name: 'brandName', index: 'brand_id', width: 120},
            {
                label: '上架', name: 'isOnSale', index: 'is_on_sale', width: 50,
                formatter: function (value) {
                    return transIsNot(value);
                }
            },
            {label: '售价', name: 'unitPrice', index: 'unit_price', width: 30},
            {
                label: '操作',name: 'status', width: 120, align: 'center', sortable: false, formatter:function (value, col, row) {
                	var resultStr = '<button class="btn btn-outline btn-info" onclick="vm.updateById(' + row.id + ')"><i class="fa fa-info-circle"></i>&nbsp;修改</button>';
                	return resultStr;
                }
            },
        ]
    });
    vm.init();
});
var vm = new Vue({
    el: '#rrapp',
    data: {
    	categoryId:null,
    	category:null,
    	isDaBaoGoods:false,
        showList: true,
        title: null,
        uploadList: [],
        imgName: '',
        visible: false,
        wxUrl:'',
        goods: {
            primaryPicUrl: '',
            listPicUrl: '',
            categoryId: '',
            isOnSale: 1,
            isNew: 1,
            isAppExclusive: 0,
            isLimited: 0,
            isHot: 0,
            categoryName: '',
            audioUrl:'',
            testAudioUrl:'',
            goodsType:0,
        	counterPrice:0,
            unitPrice:0,
            retailPrice:0,
            marketPrice:0,
            appExclusivePrice:0
        },
        ruleValidate: {
            name: [
                {required: true, message: '名称不能为空', trigger: 'blur'}
            ],
            goodsType: [
            	{required: true, message: '商品类型不能为空', trigger: 'blur'}
        	]
        },
        q: {
            name: '',goodsType:null,categoryId:null,categoryName:''
        },
        goodsTypeList:[],
        articleNum:1,
    },
    methods: {
    	init:function(){
            vm.getGoodsType();
            vm.getCategory();
            vm.getArticleNum();
    	},
    	getCategory:function(){
            Ajax.request({
                url: "../category/info/" + vm.categoryId,
                async: true,
                successCallback: function (r) {
                    vm.category = r.category;
                }
            });
    	},
    	getGoodsType:function(){
            Ajax.request({
                url: "../sys/config/list/goodsType",
                async: true,
                successCallback: function (r) {
                    vm.goodsTypeList = r.configList;
                }
            });
    	},
    	getArticleNum:function(){
            Ajax.request({
                url: "../goods/articlenum/" + vm.categoryId,
                async: true,
                successCallback: function (r) {
                    vm.articleNum = r.articleNum + 1;
                }
            });
    	},
        query: function () {
            vm.reload();
        },
        add: function () {
            vm.showList = false;
            vm.title = "新增";
            vm.uploadList = [];
            vm.goods = {
                primaryPicUrl: '',
                listPicUrl: '',
                isOnSale: 1,
                isNew: 1,
                isAppExclusive: 0,
                isLimited: 0,
                isHot: 0,
                categoryName: vm.category.name,
                audioUrl:'',
                testAudioUrl:'',
                categoryId:vm.categoryId,
                goodsType:0,
                sortOrder:vm.articleNum,
            	counterPrice:0,
                unitPrice:0,
                retailPrice:0,
                marketPrice:0,
                appExclusivePrice:0,
                goodsSn:"第"+ vm.articleNum + "章",
                listPicUrl:vm.category.iconUrl,
                goodsUnit:vm.category.frontName,
            };
            vm.editableAgain();
            $('#goodsDesc').editable('setHTML', '');
            $('#testContent').editable('setHTML', '');
        },
        update: function (event) {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            vm.showList = false;
            vm.title = "修改";
            vm.uploadList = [];
            vm.getInfo(id);
        },
        updateById: function (id) {
            vm.showList = false;
            vm.title = "修改";
            vm.uploadList = [];
            vm.getInfo(id);
        },
        saveOrUpdate: function (event) {
            var url = vm.goods.id == null ? "../goods/save" : "../goods/update";
            vm.goods.goodsDesc = $('#goodsDesc').editable('getHTML');
            vm.goods.testContent = $('#testContent').editable('getHTML');
            vm.goods.goodsImgList = vm.uploadList;
            Ajax.request({
                type: "POST",
                url: url,
                contentType: "application/json",
                params: JSON.stringify(vm.goods),
                successCallback: function (r) {
                    alert('操作成功', function (index) {
                        vm.reload();
                    });
                }
            });
        },
        enSale: function () {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            confirm('确定要上架选中的章节？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../goods/enSale",
                    params: JSON.stringify(id),
                    contentType: "application/json",
                    type: 'POST',
                    successCallback: function () {
                        alert('提交成功', function (index) {
                            vm.reload();
                        });
                    }
                });
            });
        },
        unSale: function () {
            var id = getSelectedRow("#jqGrid");
            if (id == null) {
                return;
            }
            confirm('确定要下架选中的章节？', function () {

                Ajax.request({
                    type: "POST",
                    url: "../goods/unSale",
                    contentType: "application/json",
                    params: JSON.stringify(id),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();;
                        });
                    }
                });

            });
        },
        del: function (event) {
            var ids = getSelectedRows("#jqGrid");
            if (ids == null) {
                return;
            }

            confirm('确定要删除选中的记录？', function () {
                Ajax.request({
                    type: "POST",
                    url: "../goods/delete",
                    contentType: "application/json",
                    params: JSON.stringify(ids),
                    successCallback: function (r) {
                        alert('操作成功', function (index) {
                            vm.reload();;
                        });
                    }
                });

            });
        },
        getInfo: function (id) {
            Ajax.request({
                url: "../goods/info/" + id,
                async: true,
                successCallback: function (r) {
                    vm.goods = r.goods;
                    vm.editableAgain();
                    $('#goodsDesc').editable('setHTML', vm.goods.goodsDesc);
                    $('#testContent').editable('setHTML', vm.goods.testContent);
                	if(vm.goods.goodsType == 99){
                		vm.isDaBaoGoods = true;
                	}else{
                		vm.isDaBaoGoods = false;
                	}
                }
            });
        },
        reload: function (event) {
            vm.showList = true;
            var page = $("#jqGrid").jqGrid('getGridParam', 'page');
            $("#jqGrid").jqGrid('setGridParam', {
                postData: {'name': vm.q.name,'goodsType':vm.q.goodsType,'categoryId':vm.q.categoryId},
                page: page
            }).trigger("reloadGrid");
            vm.handleReset('formValidate');
            vm.getArticleNum();
        },
        handleView(name) {
            this.imgName = name;
            this.visible = true;
        },
        handleSuccess(res, file) {
            // 因为上传过程为实例，这里模拟添加 url
            file.imgUrl = res.url;
            file.name = res.url;
            vm.uploadList.add(file);
        },
        handleBeforeUpload() {
            const check = this.uploadList.length < 5;
            if (!check) {
                this.$Notice.warning({
                    title: '最多只能上传 5 张图片。'
                });
            }
            return check;
        },
        handleSubmit: function (name) {
            handleSubmitValidate(this, name, function () {
                vm.saveOrUpdate()
            });
        },
        handleFormatError: function (file) {
            this.$Notice.warning({
                title: '文件格式不正确',
                desc: '文件 ' + file.name + ' 格式不正确，请上传 jpg 或 png 格式的图片。'
            });
        },
        handleMaxSize: function (file) {
            this.$Notice.warning({
                title: '超出文件大小限制',
                desc: '文件 ' + file.name + ' 太大，不能超过 2M。'
            });
        },
        handleReset: function (name) {
            handleResetForm(this, name);
        },
        handleSuccessPicUrl: function (res, file) {
            vm.goods.primaryPicUrl = file.response.url;
        },
        handleSuccessListPicUrl: function (res, file) {
            vm.goods.listPicUrl = file.response.url;
        },
        handleSuccessSubPicUrl: function (res, file) {
            vm.goods.subPicUrl = file.response.url;
        },
        handleSuccessSubPicUrlb: function (res, file) {
            vm.goods.subPicUrlb = file.response.url;
        },
        handleSuccessAudioUrl: function (res, file) {
            vm.goods.audioUrl = file.response.url;
        },
        handleSuccessPreludeAudioUrl: function (res, file) {
            vm.goods.preludeAudioUrl = file.response.url;
        },
        handleSuccessTestAudioUrl: function (res, file) {
            vm.goods.testAudioUrl = file.response.url;
        },
        eyeImagePicUrl: function () {
            var url = vm.goods.primaryPicUrl;
            eyeImage(url);
        },
        eyeImageSubPicUrl: function () {
            var url = vm.goods.subPicUrl;
            eyeImage(url);
        },
        eyeImageSubPicUrlb: function () {
            var url = vm.goods.subPicUrlb;
            eyeImage(url);
        },
        eyeImageListPicUrl: function () {
            var url = vm.goods.listPicUrl;
            eyeImage(url);
        },
        eyeImage: function (e) {
            eyeImage($(e.target).attr('src'));
        },
        fetchArticle:function(){
            Ajax.request({
			    url: "../mpmsg/article",
                params: {url:encodeURIComponent(vm.wxUrl)},
                type: "POST",
                successCallback: function (r) {
                	vm.goods.name = r.article.title;
                	vm.goods.keywords = r.article.author;
                	vm.goods.primaryPicUrl = r.article.imgUrl;
                	vm.goods.listPicUrl = r.article.imgUrl;
                    vm.editableAgain();
                    $('#goodsDesc').editable('setHTML', r.article.content);
                    $('#testContent').editable('setHTML', r.article.firstP);
                    vm.goods.goodsBrief = r.article.desc;
                    vm.goods.promotionDesc = r.article.desc;
                    alert('获取成功，请修改后发布!');
				}
			});
        },
        editableAgain(){
            $('#goodsDesc').editable({
                inlineMode: false,
                alwaysBlank: true,
                height: '500px', //高度
                minHeight: '200px',
                language: "zh_cn",
                spellcheck: false,
                plainPaste: true,
                enableScript: false,
                imageButtons: ["floatImageLeft", "floatImageNone", "floatImageRight", "linkImage", "replaceImage", "removeImage"],
                allowedImageTypes: ["jpeg", "jpg", "png", "gif"],
                imageUploadURL: '../sys/oss/upload',
                imageUploadParams: {id: "edit"},
                imagesLoadURL: '../sys/oss/queryAll'
            });
            
            $('#testContent').editable({
                inlineMode: false,
                alwaysBlank: true,
                height: '200px', //高度
                minHeight: '200px',
                language: "zh_cn",
                spellcheck: false,
                plainPaste: true,
                enableScript: false,
                imageButtons: ["floatImageLeft", "floatImageNone", "floatImageRight", "linkImage", "replaceImage", "removeImage"],
                allowedImageTypes: ["jpeg", "jpg", "png", "gif"],
                imageUploadURL: '../sys/oss/upload',
                imageUploadParams: {id: "edit"},
                imagesLoadURL: '../sys/oss/queryAll'
            });        	
        },
        selectGoodsType(){
        	if(vm.goods.goodsType == 99){
        		vm.isDaBaoGoods = true;
        		vm.goods.parentId = null;
        	}else{
        		vm.isDaBaoGoods = false;
        	}
        },
        freeRead(){
        	vm.goods.counterPrice = 0;
        	vm.goods.unitPrice = 0;
        	vm.goods.retailPrice = 0;
        	vm.goods.marketPrice = 0;
        	vm.goods.appExclusivePrice = 0;
        },
    },
    mounted() {
    },
});